package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
)

type LoginlogSrv struct{}

func (r *LoginlogSrv) Pagination(req request.LoginlogPagination) response.Resp {
	offset := (req.PageIndex - 1) * req.PageSize
	where := "1=1"
	if req.Keyword != "" {
		where += " AND (`username` = '" + req.Keyword + "' OR `ip` = '" + req.Keyword + "' OR `info` LIKE '%" + req.Keyword + "%')"
	}
	var total int64
	err := global.Gorm.Model(&model.Loginlog{}).Where(where).Count(&total).Error
	if err != nil {
		return response.ErrQuery
	}
	var loginlog []model.Loginlog
	err = global.Gorm.Where(where).Offset(offset).Limit(req.PageSize).Order("id desc").Find(&loginlog).Error
	if err != nil {
		return response.ErrQuery
	}
	if len(loginlog) == 0 {
		return response.OK.WithData(map[string]interface{}{
			"total": 0,
			"list":  loginlog,
		})
	}

	return response.OK.WithData(map[string]interface{}{
		"total": total,
		"list":  loginlog,
	})
}

func (r *LoginlogSrv) FindByID(id uint) (error, model.Loginlog) {
	var loginlog model.Loginlog
	err := global.Gorm.Where("id = ?", id).First(&loginlog).Error

	return err, loginlog
}

func (r *LoginlogSrv) Del(id uint) response.Resp {
	err, loginlog := r.FindByID(id)
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	if loginlog.ID == 0 {
		return response.ErrRecordNotFound
	}
	// 数据删除
	if err := global.Gorm.Unscoped().Delete(&loginlog).Error; err != nil {
		return response.ErrDel.SetMsg(err.Error())
	}
	return response.OK
}